package demo.study.concurrent;

public class Counter {
	
	String name;

	public Counter(String name) {
		super();
		this.name = name;
	}

	/**
	 * 您只能在有限的一些情形下使用 volatile 变量替代锁。要使 volatile 变量提供理想的线程安全，必须同时满足下面两个条件：
	 * 对变量的写操作不依赖于当前值。 该变量没有包含在具有其他变量的不变式中。
	 */
	//ConcurrentHashMap 一个同步的Map,效率比HashTable高
	// volatile比synchronized效率高,但是不能乱用
	public static volatile int count = 0;
	
	public int no = 0;

	// synchronized
	public static void inc() {

		//synchronized(Counter.class) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
			}

		
			count++;
		//}
		
		System.out.println("inc" + count);
	}
	
	public static void m() {
		System.out.println("Counter.m()");
	}
	
	// synchronized
	public void incNonStatic() {
		
		//synchronized(this) {// this是指锁住改对象,锁住的是对象级别
		synchronized(Counter.class) {// class是指锁住该类所生产的所有对象,是类级别
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
		}
		
		
		no++;
		}
		
		System.out.println(name + "incNonStatic" + no);
	}
	
	// 所谓同步只是方法级别的,和其他方法没有关系
	public void mNonStatic() {
		System.out.println("CounterNonStatic.m()");
	}

	public static void main(String[] args) {
		
		final Counter c = new Counter("c");

		Thread threads[] = new Thread[1000];
		for (int i = 0; i < 1000; i++) {
			threads[i] = new Thread(new Runnable() {
				@Override
				public void run() {
					c.incNonStatic();
				}
			});
			threads[i].start();
			//c.mNonStatic();
			Counter c2 = new Counter("ccccccccc");
			c2.incNonStatic();
		}
		for (int i = 0; i < 1000; i++) {
			try {
				threads[i].join();// 必须join
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("运行结果:Counter.count=" + c.no);
		
/*		Thread threads[] = new Thread[1000];
		for (int i = 0; i < 1000; i++) {
			threads[i] = new Thread(new Runnable() {
				@Override
				public void run() {
					Counter.inc();
				}
			});
			threads[i].start();
			Counter.m();
		}
		for (int i = 0; i < 1000; i++) {
			try {
				threads[i].join();// 必须join
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("运行结果:Counter.count=" + Counter.count);
*/	}
}